package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.bean.DimJoinFunction;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.util.DimUtil;
import com.atguigu.gmall.realtime.util.HbaseUtil;
import com.atguigu.gmall.realtime.util.RedisUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

/**
 * @author Felix
 * @date 2023/9/2
 * 维度关联的基本实现
 * 模板方法设计模式：在父类中定义完成某一个功能的核心算法的骨架(步骤)，但是具体的某些步骤需要延迟到子类中去实现(抽象)
 *               在不改变父类核心算法骨架的前提下，每一个子类都可以有自己不同的实现。
 */
public abstract class DimMapFunction<T> extends RichMapFunction<T,T> implements DimJoinFunction<T> {
    private Jedis jedis;
    private Connection conn;
    private String tableName;

    public DimMapFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        conn = HbaseUtil.getHbaseConnection();
        jedis = RedisUtil.getJedis();
    }

    @Override
    public void close() throws Exception {
        HbaseUtil.closeHbaseConnection(conn);
        RedisUtil.closeJedis(jedis);
    }
    @Override
    public T map(T obj) throws Exception {
        //根据流中的对象获取要关联的维度主键
        String key = getKey(obj);
        //根据维度的主键获取维度对象
        JSONObject dimInfoJsonObj = DimUtil.getDimInfo(jedis, conn, GmallConfig.HBASE_NAMESPACE, tableName, key);
        if(dimInfoJsonObj != null){
            //将维度对象的属性补充到流中对象上
            join(obj,dimInfoJsonObj);
        }
        return obj;
    }


}
